<template>
  <div>
    <el-drawer
      v-el-drag-dialog
      title="订单打印列表"
      :visible.sync="visible"
      size="80%"
      @close="reset"
    >
      <div class="center">
        <lb-table
          ref="lbTable"
          v-el-height-adaptive-table="{bottomOffset:65}"
          border
          highlight-current-row
          element-loading-text="加载中"
          :column="tableData.column"
          :data="tableData.data"
          @selection-change="handleSelectionChange"
        />
      </div>
      <div class="demo-drawer__footer">
        <div class="btn-group">
          <div class="btns">
            <el-button @click="visible = false"> 关闭 </el-button>
            <el-button :loading="$loadingPlugin.print" type="primary" @click="printOrder"> 打印 </el-button>
          </div>
        </div>
      </div>
    </el-drawer>
    <csm-detail
      ref="csmDetail"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
  </div>

</template>

<script>
  import { parseTime, toRMB } from '@/filters'
  import { getPrinterType, batchOrderPrintTable, newReceiptOrderDetail, queryMap, queryTransactorList, queryMapOrder, queryCsmInfo, orderbillRecord } from '@/api'
  import { formatColumnMap } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'
  import OrderDetail from '@/views/orderCenter/orderManage/components/OrderDetails'
  export default {
    name: 'orderDetailList',
    filters: {
      parseTime
    },
    components: {
      CsmDetail,
      OrderDetail
    },
    props: {
      treeData: {
        type: Array,
        default: []
      },
      routerType: {
        type: Number,
        default: 0
      },
      localStorageTp: {
        type: Object
      }
    },
    data() {
      return {
        visible: false,
        tableData: {
          total: 0,
          column: [
            { type: 'selection', width: '40' },
            { label: '单号',
              prop: 'orderCode',
              width: 100,
              render: (h, { row }) => row.orderCode ? <el-link underline={false} onClick={() => this.openOrderDetail(row)}>{row.orderCode}</el-link> : <span>{row.orderCode}</span>
            },
            { label: '地址', prop: 'csmAddress', width: 180, showOverflowTooltip: true },
            { label: '客户名称', prop: 'csmName' },
            { label: '客户编号',
              prop: 'csmCode',
              width: 100,
              render: (h, { row }) => row.csmCode ? <el-link underline={false} onClick={() => this.openCsm(row)}>{row.csmCode}</el-link> : <span>{row.csmCode}</span>
            },
            { label: '客户电话', prop: 'contactPhone', width: 120 },
            { label: '备注', prop: 'remark', width: 150, showOverflowTooltip: true },
            { label: '金额', prop: 'decimalSpare4', align: 'right' },
            { label: '订单状态', prop: 'orderStatus', render: (h, { row }) => <span>{this.statusMap.length > 0 ? this.statusMap.filter(item => item.value === row.orderStatus)[0].desc : ''}</span> },
            { label: '配送员', prop: 'ownerName' },
            {
              prop: 'driverName',
              label: '大车司机',
              showOverflowTooltip: true
            },
            {
              prop: 'escortName',
              label: '押运员',
              showOverflowTooltip: true
            },
            {
              label: '下单时间',
              prop: 'transactTime',
              width: 180,
              render: (h, { row }) => (
              <span>
                {row.transactTime &&
                  parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
            },
            {
              prop: 'appointmentDt',
              label: '预约时间',
              width: 200,
              render: (h, { row }) => {
                return (
                  <div class={this.getClass(row)}>
                    {(row.appointmentDt && row.dateTimeSpare1) && <span>{parseTime(row.dateTimeSpare1, '{h}:{i}') === '23:59' ? parseTime(row.appointmentDt, '{y}-{m}-{d}') : parseTime(row.appointmentDt, '{y}-{m}-{d} {h}:{i}') + ' 至 ' + parseTime(row.dateTimeSpare1, '{h}:{i}')}</span>}
                  </div>
                )
              }
            },
            { label: '商品数量', prop: 'goodsCount', width: 50, align: 'right' },
            { label: '商品详情', prop: 'goodsDesc', width: 200 }
          ],
          data: []
        },
        multipleSelection: [],
        customerType: [],
        paymentMethod: [],
        statusMap: [],
        calcTypeList: [], // 收款方式枚举
        paymenFilList: [], // 付款方式枚举
        transactorList: [], // 处理人列表
        orderStatusMap: [],
        orderFlagMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        orderSourceMap: []
      }
    },
    methods: {
      open(temp) {
        return new Promise(async(resolve) => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            const res = await batchOrderPrintTable({ userId: temp.userId })
            this.tableData.data = res.data
            this.queryOptionsMap()
            this.queryOptionsMap1()
          }
        })
      },
      getClass(r) {
        if (r.overTimeType) {
          if (r.overTimeType === 1) {
            return 'yellow'
          }
          if (r.overTimeType === 2) {
            return 'red'
          }
        }
      },
      // 订单详情
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row, true)
      },
      // 打开客户
      async openCsm(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 获取状态的枚举数据
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMapOrder, { enumName: 'orderStatus' })
        ])
        this.customerType = res1.data
        this.paymentMethod = res2.data
        this.statusMap = res3.data
      },
      // 查询字典枚举
      async queryOptionsMap1() {
        const [res4, res5, res6, res7, res8, res9] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' })
        ])
        this.calcTypeList = res4.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res5.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.orderStatusMap = res6.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res7.data // 订单类型
        this.payStatusMap = res8.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.orderSourceMap = res9.data // 订单来源
        this.getTransactorList()
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      printOrder(list) {
        console.log('list', list.length)
        if (list.length) {
          this.multipleSelection = list
        }
        if (!this.multipleSelection.length) {
          this.$message.error('请勾选需要打印的订单')
          return
        }
        if (this.routerType && (!window.top.jCPrint || !window.top.jCPrint.ws)) {
          this.$message.error('打印未连接')
          return
        }
        if (!this.routerType && (!window.jCPrint || !window.jCPrint.ws)) {
          this.$message.error('打印未连接')
          return
        }
        while (this.multipleSelection.length > 0) {
          this.tryPrint2(this.multipleSelection.splice(0, 1)[0])
        }
      },
      async tryPrint(row) {
        const params = {
          orderCode: row.orderCode
        }
        const { status, data } = await newReceiptOrderDetail(params)
        if (status === 200) {
          // this.print(row, data)
          this.tryPrint1(row, data)
        }
      },
      async tryPrint1(row, items) {
        console.log('row', row)
        const params = {
          csmId: row.csmId
        }
        const { status, data } = await queryCsmInfo(params)
        if (status === 200) {
          row['lastBuyDt'] = data['lastBuyDt'] || ''
          row['score'] = data['score'] || 0
          this.print(row, items)
        }
      },
      async tryPrint2(row) {
        const params = {
          orderCode: row.orderCode
        }
        const { status, data } = await orderbillRecord(params)
        if (status === 200) {
          row = { ...row, ...data }
          row['fee1'] = data['fee1'] || 0
          row['fee2'] = data['fee2'] | 0
          row['preferentialPackageName'] = data['preferentialPackageName'] || ''
          row['preferentialCount'] = data['preferentialCount'] || 0
          // 预约时间

          var reservationDt = ''
          var day = parseTime(row.appointmentDt || row.dateTimeSpare1, '{y}-{m}-{d} ')
          if (row.appointmentDt && !row.dateTimeSpare1) {
            const time1 = parseTime(row.appointmentDt, '{h}:{i}')
            reservationDt = String.format('{0}{1}之后', day, time1)
          } else if (!row.appointmentDt && row.dateTimeSpare1) {
            const time2 = parseTime(row.dateTimeSpare1, '{h}:{i}')
            reservationDt = String.format('{0}{1}之前', day, time2)
          } else {
            const time1 = parseTime(row.appointmentDt, '{h}:{i}')
            const time2 = parseTime(row.dateTimeSpare1, '{h}:{i}')
            reservationDt = String.format('{0}{1}至{2}', day, time1, time2)
          }
          row.reservationDt = reservationDt
          console.log('row1', row)
          this.tryPrint(row)
        }
        return row
      },
      toDecimal(str, p) {
        var reg = /^(-?\d+)(\.\d+)?$/
        if (reg.test(str)) {
          return parseFloat(str).toFixed(p || 2) * 1
        }
        return 0
      },
      async print(row2, items) {
        const row = JSON.parse(JSON.stringify(row2))
        let cache = null
        if (this.routerType) {
          const res = await getPrinterType({ templateType: 38 })
          const da = JSON.parse(res.data.templateContent)

          cache = { 38: { count: 1,
                          ...da,
                          left: 0,
                          printer: 'pdf',
                          top: 0 }}
        } else {
          cache = JSON.parse(localStorage.tp)
        }
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const temp = cache['38']
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }

        row.printDt = parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}')
        // row.dateTimeSpare2 = dayjs(row.dateTimeSpare2).format('YYYY-MM-DD hh:mm')
        row.printMoney = `${row.treceivables}(${toRMB(row.treceivables)})`
        row.payMethod = ''
        // console.log(this.paymentMethodMap)
        if (row.fromPlat !== 1 && row.fromPlat !== 7) {
          for (var item in this.paymentMethodMap) {
            if ((item && row.paymentMethod) > 0) {
              row.payMethod += this.paymentMethodMap[item].desc + ','
            }
          }
          row.payMethod = (row.payMethod || '').replace(/(^,+)|(,+$)/g, '')
        }
        for (var i in items) {
          const item = items[i]
          item.goodsTotalPrice = this.toDecimal(item.gcount * item.gprince, 2).toFixed(2)
          item.gprince = this.toDecimal(item.gprince, 2).toFixed(2)
          item.fee1 = this.toDecimal(item.fee1, 2).toFixed(2)
          item.fee2 = this.toDecimal(item.fee2, 2).toFixed(2)
        }
        if (row.payStatus === 3) {
          row.printMoney = `${row.printMoney} 已支付(${formatColumnMap(
            this.paymentMethod,
            'value',
            row.payMethod,
            'desc'
          )})`
        } else {
          row.taccReceivable = ''
        }
        row.csmAddress = row.csmAddress.includes('市') ? row.csmAddress.replace(/市/, ' ').split(' ')[1] : row.csmAddress
        // row.csmTypeName = this.customerTypeMap[row.csmType] || '居民用户'
        row.csmTypeName =
          formatColumnMap(this.customerType, 'value', row.csmType, 'desc') || '居民用户'
        row.goodsDesc = row.goodsDesc.split('^')[0]
        if (items.length > 0) {
          row.price = items[0].gprince
        }
        if (row.isPickUp === 1) {
          row.orgNewName = row.orgName + '零售单(自提)'
        } else {
          row.orgNewName = row.orgName + '零售单'
        }
        if (row.preferentialCount === 0) {
          row.preferentialCount = ''
        }
        row.treceivables = this.toDecimal(row.treceivables, 2).toFixed(2)
        row.fee1 = this.toDecimal(row.fee1 / 100, 2).toFixed(2)
        row.fee2 = this.toDecimal(row.fee2 / 100, 2).toFixed(2)
        if (row.fee1 === 0) {
          row.fee1 = ''
        }
        if (row.fee2 === 0) {
          row.fee2 = ''
        }
        if (row.ownerName === null || row.ownerName === undefined) {
          row.ownerName = ''
        }
        if (row.remark === null || row.remark === undefined) {
          row.remark = ''
        }
        if (row.preferentialPackageName === null || row.preferentialPackageName === undefined) {
          row.preferentialPackageName = ''
        }
        let printcmd = {
          cmd: 2,
          title: `正在对订单${row.orderCode}进行配送单打印`,
          elements: []
        }
        printcmd = { ...printcmd, ...temp }
        const printcmd1 = JSON.parse(JSON.stringify(printcmd))
        if (this.routerType) {
          window.top.jCPrint.process(printcmd1, temp, row, items)
        } else {
          window.jCPrint.process(printcmd, temp, row, items)
        }

        delete printcmd.els
        delete printcmd1.els
        if (this.routerType) {
          if (window.top.jCPrint.firePush(JSON.stringify(printcmd1))) {
            if (this.multipleSelection.length === 0) {
              if (this.$refs['lbTable']) {
                this.$refs['lbTable'].clearSelection()
              }
              this.$message.success('打印指令已发送')
            }
          } else {
            this.$message.error('打印未连接')
          }
        } else {
          if (window.jCPrint.firePush(JSON.stringify(printcmd))) {
            if (this.multipleSelection.length === 0) {
              if (this.$refs['lbTable']) {
                this.$refs['lbTable'].clearSelection()
              }
              this.$message.success('打印指令已发送')
            }
          } else {
            this.$message.error('打印未连接')
          }
        }
      },
      reset() {
        this.visible = false
        this.multipleSelection = []
        this.tableData.data = []
        this.tableData.total = 0
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-drawer /deep/.el-drawer__body {
  padding: 0 10px;
}
.center {
  padding: 0 20px;
  .lbTable {
    height: 1000px;
  }
}
.demo-drawer__footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 55px;
  padding: 0 10px 10px 0;
  text-align: right;
  background: white;
  border: 2px solid #DCDFE6;
  .btn-group {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    margin-right: 21%;
    .btns {
      display: flex;
      margin-left: 15px;
    }
  }
}
</style>
